package com.example.administrator.lrucachedemo

import android.graphics.Bitmap
import android.util.Log
import android.util.LruCache

/**
 * Created by Administrator on 2018/3/15 0015.
 */
class ImageDownLoader {
    //用来存储缓存的数字
    private var lruCache:LruCache<String,Bitmap>?=null
    //初始化
    init {
        //获取运行的最大内存
        val maxMemory=Runtime.getRuntime().maxMemory()
        Log.d("获取运行的最大内存",maxMemory.toString())
        //默认取缓存的八分之一
        val cacheSize=(maxMemory/8).toInt()
        lruCache=object :LruCache<String,Bitmap>(cacheSize){
            override fun sizeOf(key: String?, value: Bitmap?): Int {
                return value?.byteCount?:0
            }
        }
    }
    //把Bitmap对象加入到缓存中
    fun addBitmapToMemory(key:String,bitmap:Bitmap){
        if(getBitmapFromMemCache(key)==null){
            lruCache?.put(key,bitmap)
        }
    }
    //从缓存中取出数据
    fun getBitmapFromMemCache(key:String):Bitmap?{
        return lruCache?.get(key)
    }
    //从缓存中删除指定Bitmap
    fun removeBitmapFromMemory(key: String){
        lruCache?.remove(key)
    }
    companion object {
        private val TAG="图片工具类ImageDownLoader"
    }
}